package com.example.gclove.controller;


import com.example.gclove.mapper.UserMapper;
import com.example.gclove.pojo.User;
import com.example.gclove.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin("*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    //    注册账号功能
    @PostMapping("/b")
    public String addUser(@RequestBody User user) {
        if (userMapper.selectAllByUsername(user.getUsername())) {
            return "该账号已存在!";
        } else if (user.getUsername() == 0 || user.getPassword().equals("")) {
            return "请输入账号或者密码~";
        } else {
            user.setCode((int) (System.currentTimeMillis() % 10000));
            userService.addUser(user.getUsername(), user.getPassword(), user.getCode());
            return "注册成功~";
        }
    }

    //登录功能，并根据账号和密码返回User对象
    @PostMapping("/login")
    public Map login(@RequestBody User user) {
        HashMap map = new HashMap<>();
        if (userMapper.selectAllByUsernameOrderByPassword(user.getUsername(), user.getPassword())) {
            map.put("status", "登录成功");
            map.put("myUser", userMapper.selectUserByUsernameOrderByPassword(user.getUsername(), user.getPassword()));
            return map;
        } else {
            map.put("status", "账号或者密码有误!");
            return map;
        }
    }

    //恋接对象，通过密钥，并且返回User对象
    @PostMapping("/link")
    public Map link(@RequestParam int code, @RequestParam int userId) {
        Map map = new HashMap();
        if (userMapper.selectByCode(code)) {
            User user = userMapper.addUserByCode(code);
            map.put("status", "恋接成功");
//互相连接
            userMapper.linkUser(userId, user.getId());
            userMapper.linkUser(user.getId(), userId);
            map.put("taUser", user);
            return map;
        } else {
            map.put("status", "密钥错误");
            User user = new User();
            user.setCode(0);
            map.put("taUser", user);
            return map;
        }
    }

    //检查是否已经恋接了对象，来判断是否直接跳过恋接页面并且返回一个对象
    @PostMapping("/jump")
    public User jump(@RequestBody User user) {
        User user1;
        user1 = userMapper.selectByLoveId(user.getLoveId());
        return user1;
    }


}
